package com.ruoyi.industryfrontend.service.impl;

import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.DistanceUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.industryfrontend.domain.SpaceIndustry;
import com.ruoyi.industryfrontend.mapper.*;
import com.ruoyi.industryfrontend.service.ISpaceIndustryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 产业空间Service业务层处理
 *
 * @author MagicCube
 * @date 2023-05-22
 */
@Service
public class SpaceIndustryServiceImpl implements ISpaceIndustryService {
    @Autowired
    private SpaceIndustryMapper spaceIndustryMapper;

    @Autowired
    private ProjectBuildingMapper projectBuildingMapper;

    @Autowired
    private ProjectWarehouseMapper projectWarehouseMapper;

    @Autowired
    private ProjectWorkshopMapper projectWorkshopMapper;

    @Autowired
    private ProjectApartmentMapper projectApartmentMapper;

    @Autowired
    private ProjectLandMapper projectLandMapper;

    @Autowired
    private ProjectParkMapper projectParkMapper;

    @Autowired
    private DistrictMapper districtMapper;

    @Autowired
    private SpaceCollectMapper spaceCollectMapper;

    /**
     * 查询产业空间
     *
     * @param id 产业空间主键
     * @return 产业空间
     */
    @Override
    public SpaceIndustry selectSpaceIndustryById(Long id) {
        return spaceIndustryMapper.selectSpaceIndustryById(id);
    }

    /**
     * 查询产业空间列表
     *
     * @param spaceIndustry 产业空间
     * @return 产业空间
     */
    @Override
    public List<SpaceIndustry> selectSpaceIndustryList(SpaceIndustry spaceIndustry) {
        return spaceIndustryMapper.selectSpaceIndustryList(spaceIndustry);
    }

    @Override
    public List<SpaceIndustry> selectSpaceIndustryListz(SpaceIndustry spaceIndustry, Boolean login) {
        extracted(spaceIndustry);
        List<SpaceIndustry> spaceIndustries = spaceIndustryMapper.selectSpaceIndustryListz(spaceIndustry);
//        String isPerfect = spaceIndustryMapper.checkUserIsPerfect(SecurityUtils.getUserId());
//        if (login && (isPerfect == null || isPerfect.equals("1"))) {
        return checkLogin(login, spaceIndustries);
    }

    private void checkCollection(List<SpaceIndustry> spaceIndustries) {
        //查询所有收藏的空间编码
        List<String> list = spaceCollectMapper.selectSpaceCollect(SecurityUtils.getUserId());
        //循环判断是否有收藏
        if (list != null && list.size() != 0) {
            for (SpaceIndustry industry : spaceIndustries) {
                if (list.contains(industry.getSpaceId())) {
                    industry.setCollectState(1);
                }
            }
        }
    }

    private void extracted(SpaceIndustry spaceIndustry) {
        //根据城市查询
//        List<Long> cityIds = new ArrayList<>();
//        if (spaceIndustry.getCityId()!=null){
//            cityIds.add(spaceIndustry.getCityId());
//        }else if (spaceIndustry.getCityId()==null && spaceIndustry.getProvinceId()!=null){
//            cityIds.addAll(districtMapper.selectDistrictIdList(spaceIndustry.getProvinceId()));
//        }
//        if (cityIds.size()!=0) {
//            spaceIndustry.setCityIds(cityIds);
//        }
        //出售价格
        if (spaceIndustry.getSellPrice() != null && !spaceIndustry.getSellPrice().equals("")) {
            String[] split = spaceIndustry.getSellPrice().split("~");
            spaceIndustry.setSellPriceLow(Long.parseLong(split[0]));
            if (!split[1].equals("N")) {
                spaceIndustry.setSellPriceHigh(Long.parseLong(split[1]));
            }
        }
        //租赁价格
        if (spaceIndustry.getLeasePrice() != null && !spaceIndustry.getLeasePrice().equals("")) {
            String[] split = spaceIndustry.getLeasePrice().split("~");
            spaceIndustry.setLeasePriceLow(Long.parseLong(split[0]));
            if (!split[1].equals("N")) {
                spaceIndustry.setLeasePriceHigh(Long.parseLong(split[1]));
            }
        }
    }

    /**
     * 人气查询
     *
     * @param spaceIndustry 产业信息
     * @return 结果
     */
    @Override
    public List<SpaceIndustry> selectSpaceIndustryPopularList(SpaceIndustry spaceIndustry, Boolean login) {
        extracted(spaceIndustry);
            List<SpaceIndustry> spaceIndustries = spaceIndustryMapper.selectSpaceIndustryPopularList(spaceIndustry);
        return checkLogin(login, spaceIndustries);
    }

    @NotNull
    public List<SpaceIndustry> checkLogin(Boolean login, List<SpaceIndustry> spaceIndustries) {
        if (login) {
            for (SpaceIndustry industry : spaceIndustries) {
                if (industry.getParkName() == null) {
                    industry.setParkName("");
                }
                if (industry.getSpaceName() == null) {
                    industry.setSpaceName("");
                }
            }
            checkCollection(spaceIndustries);
            return spaceIndustries;
        } else {
            for (SpaceIndustry industry : spaceIndustries) {
                if (industry.getParkName() != null && !industry.getParkName().equals("")) {
                    industry.setParkName(industry.getParkName().substring(0, 1) + "******");
                } else {
                    industry.setParkName("");
                }
                if (industry.getSpaceName() != null && !industry.getSpaceName().equals("")) {
                    industry.setSpaceName(industry.getSpaceName().substring(0, 1) + "******");
                } else {
                    industry.setSpaceName("*");
                }
            }
            return spaceIndustries;
        }
    }

    /**
     * 最新上架
     *
     * @param spaceIndustry 产业信息
     * @return 结果
     */
    @Override
    public List<SpaceIndustry> selectSpaceIndustryNewlyAddedList(SpaceIndustry spaceIndustry, Boolean login) {
        extracted(spaceIndustry);
        List<SpaceIndustry> spaceIndustries = spaceIndustryMapper.selectSpaceIndustryNewlyAddedList(spaceIndustry);
        return checkLogin(login, spaceIndustries);
    }

    @Override
    public List<SpaceIndustry> selectSpaceCheckIssueList(SpaceIndustry spaceIndustry) {
        extracted(spaceIndustry);
        spaceIndustry.setSupplyUserId(SecurityUtils.getUserId());
        List<SpaceIndustry> spaceIndustries = spaceIndustryMapper.selectSpaceIndustryListz(spaceIndustry);
        checkCollection(spaceIndustries);
        return spaceIndustries;
    }
    //    @Override
//    public List<SpaceIndustry> selectSpaceIndustryListz(SpaceIndustry spaceIndustry)
//    {
//        List<SpaceIndustry> spaceIndustries = spaceIndustryMapper.selectSpaceIndustryListz(spaceIndustry);
//        Map<Long, List<SpaceIndustry>> collect = spaceIndustries.stream().collect(Collectors.groupingBy(SpaceIndustry::getBuildType));
//        List<String> building = new ArrayList<>();
//        if (collect.get(0L)!=null&&collect.get(0L).size()!=0) {
//            for (SpaceIndustry industry : collect.get(0L)) {
//                building.add(industry.getSpaceId());
//            }
//        }
//        if (collect.get(1L)!=null&&collect.get(1L).size()!=0) {
//            for (SpaceIndustry industry : collect.get(1L)) {
//                building.add(industry.getSpaceId());
//            }
//        }
//        List<SpaceIndustry> spaceIndustryList = new ArrayList<>();
//        if (building.size() != 0) {
//             spaceIndustryList.addAll(projectBuildingMapper.selectProjectBuildingBySpaceIds(building));
//        }
//        //仓库
//        if (collect.get(2L)!=null&&collect.get(2L).size()!=0) {
//            List<String> warehouse = new ArrayList<>();
//            for (SpaceIndustry industry : collect.get(2L)) {
//                warehouse.add(industry.getSpaceId());
//            }
//            if (warehouse.size() != 0) {
//                List<SpaceIndustry> spaceIndustries1 = projectWarehouseMapper.selectProjectBuildingBySpaceIds(warehouse);
//                for (SpaceIndustry industry : spaceIndustries1) {
//                    industry.setBuildType(2L);
//                }
//                spaceIndustryList.addAll(spaceIndustries1);
//            }
//        }
//        //厂房
//        if (collect.get(3L)!=null&&collect.get(3L).size()!=0) {
//            List<String> workshop = new ArrayList<>();
//            for (SpaceIndustry industry : collect.get(3L)) {
//                workshop.add(industry.getSpaceId());
//            }
//            if (workshop.size() != 0) {
//                List<SpaceIndustry> spaceIndustries1 = projectWorkshopMapper.selectProjectBuildingBySpaceIds(workshop);
//                for (SpaceIndustry industry : spaceIndustries1) {
//                    industry.setBuildType(3L);
//                }
//                spaceIndustryList.addAll(spaceIndustries1);
//            }
//        }
//        //公寓
//        if (collect.get(4L)!=null&&collect.get(4L).size()!=0) {
//            List<String> apartment = new ArrayList<>();
//            for (SpaceIndustry industry : collect.get(4L)) {
//                apartment.add(industry.getSpaceId());
//            }
//            if (apartment.size() != 0) {
//                List<SpaceIndustry> spaceIndustries1 = projectApartmentMapper.selectProjectBuildingBySpaceIds(apartment);
//                for (SpaceIndustry industry : spaceIndustries1) {
//                    industry.setBuildType(5L);
//                }
//                spaceIndustryList.addAll(spaceIndustries1);
//            }
//        }
//        //土地
//        if (collect.get(5L)!=null&&collect.get(5L).size()!=0) {
//            List<String> land = new ArrayList<>();
//            for (SpaceIndustry industry : collect.get(5L)) {
//                land.add(industry.getSpaceId());
//            }
//            if (land.size() != 0) {
//                List<SpaceIndustry> spaceIndustries1 = projectLandMapper.selectProjectBuildingBySpaceIds(land);
//                for (SpaceIndustry industry : spaceIndustries1) {
//                    industry.setBuildType(5L);
//                }
//                spaceIndustryList.addAll(spaceIndustries1);
//            }
//        }
//        return spaceIndustryList;
//    }

    /**
     * 新增产业空间
     *
     * @param spaceIndustry 产业空间
     * @return 结果
     */
    @Override
    public int insertSpaceIndustry(SpaceIndustry spaceIndustry) {
        spaceIndustry.setCreateTime(DateUtils.getNowDate());
        return spaceIndustryMapper.insertSpaceIndustry(spaceIndustry);
    }

    /**
     * 修改产业空间
     *
     * @param spaceIndustry 产业空间
     * @return 结果
     */
    @Override
    public int updateSpaceIndustry(SpaceIndustry spaceIndustry) {
        spaceIndustry.setUpdateTime(DateUtils.getNowDate());
        return spaceIndustryMapper.updateSpaceIndustry(spaceIndustry);
    }

    /**
     * 批量删除产业空间
     *
     * @param ids 需要删除的产业空间主键
     * @return 结果
     */
    @Override
    public int deleteSpaceIndustryByIds(Long[] ids) {
        return spaceIndustryMapper.deleteSpaceIndustryByIds(ids);
    }

    /**
     * 删除产业空间信息
     *
     * @param id 产业空间主键
     * @return 结果
     */
    @Override
    public int deleteSpaceIndustryById(Long id) {
        return spaceIndustryMapper.deleteSpaceIndustryById(id);
    }

    @Override
    public void updatePageViews(String id) {
        spaceIndustryMapper.updatePageViews(id);
    }

    @Override
    public List<SpaceIndustry> selectNearbySpace(SpaceIndustry spaceIndustry) {
        List<Long> cityIds = new ArrayList<>();
        if (spaceIndustry.getCityId() != null) {
            cityIds.add(spaceIndustry.getCityId());
        } else if (spaceIndustry.getProvinceId() != null) {
            cityIds.add(spaceIndustry.getProvinceId());
            cityIds.addAll(districtMapper.selectDistrictIdList(spaceIndustry.getProvinceId()));
        }
        if (cityIds.size() != 0) {
            spaceIndustry.setCityIds(cityIds);
        }
        List<SpaceIndustry> industryList = spaceIndustryMapper.selectSpaceIndustryListx(spaceIndustry);
        List<SpaceIndustry> spaceIndustries = industryList.stream().filter(SpaceIndustry -> (!SpaceIndustry.getSpaceId().equals(spaceIndustry.getSpaceId()))).collect(Collectors.toList());
        if (spaceIndustry.getLongitude() != null && spaceIndustry.getLatitude() != null) {
            for (SpaceIndustry industry : spaceIndustries) {
                if (industry.getLongitude() != null && industry.getLatitude() != null) {
                    double distance = DistanceUtils.Distance(spaceIndustry.getLongitude(), spaceIndustry.getLatitude(), industry.getLongitude(), industry.getLatitude());
                    industry.setDistance(distance);
                }
            }
        }
        List<SpaceIndustry> collect = spaceIndustries.stream()
                .filter(SpaceIndustry -> (SpaceIndustry.getDistance() != null))
                .sorted(Comparator.comparing(SpaceIndustry::getDistance))
                .limit(5)
                .collect(Collectors.toList());
        if (collect.size() < 5) {
            List<SpaceIndustry> collect1 = spaceIndustries.stream()
                    .filter(SpaceIndustry -> (SpaceIndustry.getDistance() == null))
                    .sorted(Comparator.comparing(SpaceIndustry::getCreateTime))
                    .collect(Collectors.toList());
            for (int i = 0; i < 5 - collect.size() && i < collect1.size(); i++) {
                collect.add(collect1.get(i));
            }
        }
        return collect;
    }
}
